package com.ror.java.se.inet.tcp;

//客户端：将本地文件上传到服务器，接收服务器的反馈。
//服务器：接收客户端上传的文件，上传完毕之后给出反馈。

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class Demo02TcpFileServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);
        File localDestDir = new File("assets"
                + File.separator + "inet"
                + File.separator + "tcp"
                + File.separator + "server-dir");
        //默认文件名（采用UUID生成唯一文件名）
        String filename = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        Socket socket = ss.accept();

        //接收文件
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(localDestDir, filename)));
        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) != -1) {
            bos.write(buf, 0, len);
        }
        //把缓冲区剩下的数据继续写出
        bos.flush();

        //向客户端发送反馈
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("(服务器已成功接收文件)");
        bw.newLine();
        bw.flush();

        socket.close();
        ss.close();
    }
}
